package cn.jingyuan.swan.system.service.impl;

import cn.jingyuan.bee.utils.StringUtils;
import cn.jingyuan.swan.cloud.core.WarnExceptionUtils;
import cn.jingyuan.swan.system.domain.gateway.dao.GatewayRouteDao;
import cn.jingyuan.swan.system.domain.gateway.entity.GatewayRoute;
import cn.jingyuan.swan.system.service.GatewayRouteService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GatewayRouteServiceImpl implements GatewayRouteService {

    @Resource
    GatewayRouteDao gatewayRouteDao;

    @Override
    public Long addRoute(GatewayRoute route) {
        Date currentTime = new Date();

        route
            .setIsPersist(0)
            .setCreateTime(currentTime)
            .setUpdateTime(currentTime);

        return route.getRouteId();
    }

    @Override
    public Integer removeRoute(Long routeId) {
        GatewayRoute saved = getById(routeId);
        if (saved != null && saved.getIsPersist().equals(1)) {
            throw WarnExceptionUtils.newInstance("保留数据,不允许删除!");
        }

        return gatewayRouteDao.delete(routeId);
    }

    @Override
    public Integer removeRoute(List<Long> routeIds) {
        return gatewayRouteDao.deletes(routeIds);
    }

    @Override
    public void updateRoute(GatewayRoute route) {
        if (StringUtils.isBlank(route.getPath())) {

        }

        GatewayRoute saved = getById(route.getRouteId());
        if (null == saved) {
            throw WarnExceptionUtils.newInstance("数据错误");
        }

        if (saved.getIsPersist().equals(1)) {

        }

        if (!saved.getRouteName().equals(route.getRouteName())) {
            // 和原来不一致重新检查唯一性
            if (Boolean.TRUE.equals(isExist(route.getRouteName()))) {

            }
        }

        gatewayRouteDao.update(route);
    }

    @Override
    public List<GatewayRoute> getRoutes() {
        LambdaQueryWrapper<GatewayRoute> wrapper = new LambdaQueryWrapper();
        wrapper.eq(GatewayRoute::getStatus, 1);

        return gatewayRouteDao.listByQueryWrapper(wrapper);
    }

    @Override
    public GatewayRoute getById(Long routeId) {
        return gatewayRouteDao.get(routeId);
    }

    @Override
    public GatewayRoute getByRouteName(String routeName) {
        return gatewayRouteDao.getByRouteName(routeName);
    }

    @Override
    public Boolean isExist(Long routeId) {
        return (null != gatewayRouteDao.get(routeId));
    }

    @Override
    public Boolean isExist(String routeName) {
        return (null != this.getByRouteName(routeName));
    }

}
